<?php

//No direct acesss
defined('_JEXEC') or die();

jimport('joomla.application.component.model');
jimport('joomla.filesystem.folder');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.path');
jimport('joomla.client.helper');

class SimplelistingModelManage extends JModel {
        var $_data = null;
	var $_total = null;
	var $_pagination = null;
	var $_table_prefix = null;


    function __construct()
    {
        parent::__construct();

        global $mainframe, $context;

        $this->_table_prefix = '#__simplelisting';
        $params =&$mainframe->getParams();

        $limit	= $mainframe->getUserStateFromRequest( $context.'limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
        $limitstart = JRequest::getVar('limitstart', 0, '', 'int');
        $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);

        $this->setState('limit', $limit);
        $this->setState('limitstart', $limitstart);

    }

    function getData()
    {
        if (empty($this->_data)) {
            $query = $this->_buildQuery();
            $this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
        }
        return $this->_data;
    }

    function getTotal()
    {
        if (empty($this->_total)) {
            $query = $this->_buildQuery();
            $this->_total = $this->_getListCount($query);
        }
        return $this->_total;
    }

    function getPagination()
    {
        if (empty($this->_pagination)) {
            jimport('joomla.html.pagination');
            $this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
        }
        return $this->_pagination;
    }

    function _buildQuery()
    {
        $where = $this->_buildContentWhere();
        $orderby = $this->_buildContentOrderBy();

        $query = 'SELECT a.*,'.
        ' u.name as `username`, u.email as `email`, u.id as `userid`,'.
        ' t.name as `type`, ca.name as `category`, l.name as `layout`, co.name as `country`, cd.telephone as `tel`, cd.mobile `mobile`, cd.fax `fax`'.
        ' FROM '.$this->_table_prefix.' AS a' .
        ' LEFT JOIN '.$this->_table_prefix.'_types AS t ON t.id = a.type_id '.
        ' LEFT JOIN '.$this->_table_prefix.'_categories AS ca ON ca.id = a.category_id'.
        ' LEFT JOIN '.$this->_table_prefix.'_layouts AS l ON l.id = a.layout_id'.
        ' LEFT JOIN '.$this->_table_prefix.'_countries AS co ON co.id = a.countries_id'.
        ' LEFT JOIN #__users AS u ON u.id = a.create_by' .
        ' LEFT JOIN #__contact_details AS cd ON cd.user_id = a.create_by' .
        $where
        .$orderby;
        return $query;
    }

    function _buildContentWhere()
    {
        global $mainframe;
        $user =& JFactory::getuser();
        $params =&$mainframe->getParams();
        return $where;


    }

    function _buildContentOrderBy()
    {
        global $mainframe, $context;

        $filter_order     = $mainframe->getUserStateFromRequest( $context.'filter_order',      'filter_order', 	  'ordering' );
        $filter_order_Dir = $mainframe->getUserStateFromRequest( $context.'filter_order_Dir',  'filter_order_Dir', '' );

        if ($filter_order == 'a.ordering'){
                $orderby 	= ' ORDER BY a.name, a.ordering ';
        } else {
                $orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir.', a.date_created DESC, ca.name ASC ,a.name ASC, a.ordering ASC';
        }

        return $orderby;
    }

       
    function getSimplelistingLists($id){
        $query = 'SELECT a.*,
        u.name as `username`, u.email as `email`,
        t.name as `type`, ca.name as `category`, l.name as `layout`, fa.name as `facility`,
        cd.telephone as `tel`, cd.mobile as `mobile`, cd.fax as `fax`, cd.country as `usercountry`,cd.misc as `misc`, ct.name as `country`, et.name as `extra`
        FROM '.$this->_table_prefix.' AS a
        LEFT JOIN '.$this->_table_prefix.'_types AS t ON t.id = a.type_id
        LEFT JOIN '.$this->_table_prefix.'_categories AS ca ON ca.id = a.category_id
        LEFT JOIN '.$this->_table_prefix.'_countries AS ct ON ct.id = a.countries_id
        LEFT JOIN '.$this->_table_prefix.'_extras AS et ON et.id = a.extra_id
        LEFT JOIN '.$this->_table_prefix.'_layouts AS l ON l.id = a.layout_id
        LEFT JOIN '.$this->_table_prefix.'_facilities AS fa ON fa.id = a.facilities
        LEFT JOIN #__users AS u ON u.id = a.create_by
        LEFT JOIN #__contact_details AS cd ON cd.user_id = a.create_by
        WHERE a.id = '.$id;
        $db = $this->getDBO();
        $db->setQuery($query);
        $simplelisting = $db->loadObject();

        if ($simplelisting === null)
        JError::raiseError (500, JText::_('LISTING_NOT_FOUND_MSG'));
        else
        return $simplelisting;
    }

    function getNewSimplelisting()
    {
        $simplelistingTableRow =& $this->getTable('simplelisting');
        $simplelistingTableRow->id = 0;
        $simplelistingTableRow->simplelisting = '';
        return $simplelistingTableRow;
    }

    function saveSimplelisting($simplelisting)
    {
        $simplelistingTableRow =& $this->getTable('simplelisting');
        $simplelistingTableRow->reset();
        $simplelistingTableRow->reorder();
        $simplelistingTableRow->set( 'ordering', $simplelistingTableRow->getNextOrder());

        if (!$simplelistingTableRow->bind($simplelisting)) {
                JError::raiseError(500, JText::_('ERROR_BINDING_DATA_MSG'));
        }

        if (!$simplelistingTableRow->check()) {
                JError::raiseError(500, JText::_('INVALID_DATA_MSG'));
        }

        if (!$simplelistingTableRow->store()) {
                $errorMessage = $simplelistingTableRow->getError();
                JError::raiseError(500, JText::_('ERROR_BINDING_DATA_MSG').$errorMessage);
        }
    }

   function deleteSimplelisting($arrayIDs)
    {
        $gallery_num = implode(',',$arrayIDs);
        $item_gallery_dir = JPATH_ROOT .DS . 'components' . DS . 'com_simplelisting'.DS.'images'.DS.'gallery' . DS . $gallery_num;

        $query = "DELETE FROM #__simplelisting, #__simplelisting_favourite
        USING #__simplelisting
        LEFT JOIN #__simplelisting_favourite ON #__simplelisting.id = #__simplelisting_favourite.simplelisting_id
        WHERE #__simplelisting.id IN (".implode(',', $arrayIDs).")";
        $db = $this->getDBO();
        $db->setQuery($query);
        if (!$db->query()){
                $errorMessage = $this->getDBO()->getErrorMsg();
                JError::raiseError(500, JText::_('ERROR_DELETING_ITEM_MSG').$errorMessage);
        }
        if ( JFolder::exists($item_gallery_dir) ) {JFolder::delete($item_gallery_dir);

        }
    }


     function publish($cid = array(), $publish=1)
    {
        if (count( $cid ))
        {
            $cids = implode( ',', $cid );

            $query = 'UPDATE #__simplelisting'
                    . ' SET published = ' . intval( $publish )
                    . ' WHERE id IN ( '.$cids.' )'
                    ;
            $db = $this->getDBO();
            $db->setQuery($query);
            if (!$db->query()){
                    $errorMessage = $this->getDBO()->getErrorMsg();
                    JError::raiseError(500, JText::_('ERROR_UPDATING_MSG').$errorMessage);
            }
        }
    }

    function uploadFile($file, $id)
    {

        $base_upload_dir = JPATH_ROOT.DS . 'components' . DS . 'com_simplelisting'.DS.'images'.DS.'gallery';
        if ( !JFolder::exists($base_upload_dir) ) { JFolder::create($base_upload_dir); }
        $upload_dir = $base_upload_dir . DS . $id;
        if ( !JFolder::exists($upload_dir) ) { JFolder::create($upload_dir); }
	$filename = JPath::clean(strtolower('main.jpg'));
        $filepath = $upload_dir.DS.$filename;
        $allowed = array('image/jpeg', 'image/png', 'image/gif', 'image/JPG', 'image/jpg', 'image/pjpeg', 'images/x-png', 'images/PNG');
        $type = $file['type'];

        if (!in_array($type, $allowed)) 
        {
            echo "<script> alert('The file you are trying to upload is not supported.');
            window.history.back();</script>\n";
            exit;
        }
        else
        {
            $ext = JFile::getExt($file['name']);//Get extension of the file

            switch ($ext)
            {
                 case 'jpeg':
                 case 'pjpeg':
                 case 'JPG':
                 case 'jpg':
                $src = ImageCreateFromJpeg($file['tmp_name']);
                break;

                case 'png':
                case 'PNG':
                case 'x-png':
                $src = ImageCreateFromPng($file['tmp_name']);
                break;

                case 'gif':
                $src = ImageCreateFromGif($file['tmp_name']);
                break;

            }

            list($width,$height)=getimagesize($file['tmp_name']);
            $newwidth=600;//set file width to 600
            $newheight=($height/$width)*600;//the height are set according to ratio
            $tmp=imagecreatetruecolor($newwidth,$newheight);
            imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);//resample the image

            switch ($ext)
            {
                  case 'jpeg':
                  case 'pjpeg':
                  case 'JPG':
                  case 'jpg':
                  $statusupload = imagejpeg($tmp,$filepath,100);//upload the image
                  break;

                  case 'png':
                  case 'PNG':
                  case 'x-png':
                  $statusupload =  imagepng($tmp,$filepath,8);//upload the image
                  break;

                 case 'gif':
                  $statusupload = imagegif($tmp,$filepath,100);//upload the image
                  break;
            }
            chmod($filepath , 0777);
        }

    }

    function uploadFiles($file, $id)
    {
        $base_upload_dir = JPATH_ROOT.DS . 'components' . DS . 'com_simplelisting'.DS.'images'.DS.'gallery';
        if ( !JFolder::exists($base_upload_dir) ) { JFolder::create($base_upload_dir); }

        $upload_dir = $base_upload_dir . DS . $id . DS . 'second';
        if ( !JFolder::exists($upload_dir) ) { JFolder::create($upload_dir); }


        for($i=0;$i<count($file['name']);$i++)
        {
            $datetimes = date('Ymd-His');
            $filename = JPath::clean(strtolower($datetimes.'.jpg'));
            $filepath = $upload_dir.DS.$filename;
            $allowed = array('image/jpeg', 'image/png', 'image/gif', 'image/JPG', 'image/jpg', 'image/pjpeg', 'images/x-png', 'images/PNG');

            if (!in_array($file['type'][$i], $allowed))
        {
            echo "<script> alert('The file you are trying to upload is not supported.');
            window.history.back();</script>\n";
            exit;
        }

        else
        {
            $ext = JFile::getExt($file['name'][$i]);//Get extension of the file

            switch ($ext)
            {
                 case 'jpeg':
                 case 'pjpeg':
                 case 'JPG':
                 case 'jpg':
                $src = ImageCreateFromJpeg($file['tmp_name'][$i]);
                break;

                 case 'png':
                 case 'PNG':
                 case 'x-png':
                $src = ImageCreateFromPng($file['tmp_name'][$i]);
                break;

                case 'gif':
                $src = ImageCreateFromGif($file['tmp_name'][$i]);
                break;
            }

                list($width,$height)=getimagesize($file['tmp_name'][$i]);
                $newwidth=600;//set file width to 600
                $newheight=($height/$width)*600;//the height are set according to ratio
                $tmp=imagecreatetruecolor($newwidth,$newheight);
                imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);//resample the image

                switch ($ext)
                {
                  case 'jpeg':
                  case 'pjpeg':
                  case 'JPG':
                  case 'jpg':
                  $statusupload = imagejpeg($tmp,$filepath,100);//upload the image
                  break;

                  case 'png':
                  case 'PNG':
                  case 'x-png':
                  $statusupload =  imagepng($tmp,$filepath,8);//upload the image
                  break;

                 case 'gif':
                  $statusupload = imagegif($tmp,$filepath,100);//upload the image
                  break;
            }
            chmod($filepath , 0777);

        }

    }
    }

     function deleteFile($id)
    {
        $path = JPATH_ROOT.'/components/com_simplelisting/images/gallery/'.$id.'/';
        $file = $path.'main.jpg';
        chmod($file , 0777);
        JFile::delete($file);

    }

    function deleteFiles($id, $image)
    {
        $base_upload_dir = JPATH_ROOT.'/components/com_simplelisting/images/gallery/'.$id.'/second/';
        $file = $base_upload_dir.$image;
        chmod($file , 0777);
        JFile::delete($file);
        $image = JFolder::files( $base_upload_dir );
        if(empty($image)){
            JFolder::delete($base_upload_dir);
        }
    }
}
?>
